/**
 * Copyright (c) 2016-2019 九点科技 All rights reserved.
 *
 * https://www.9dyun.cn
 *
 * 版权所有，侵权必究！
 */

package com.dian.modules.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dian.common.exception.RRException;
import com.dian.common.server.CommonService;
import com.dian.common.utils.*;
import com.dian.modules.base.dao.BaseConfigDao;
import com.dian.modules.base.entity.BaseConfigEntity;
import com.dian.modules.base.service.BaseConfigService;
import  com.dian.common.enums.ValidEnum;
import com.dian.modules.sys.redis.SysConfigRedis;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service("baseConfigService")
public class BaseConfigServiceImpl extends ServiceImpl<BaseConfigDao, BaseConfigEntity> implements BaseConfigService {
	@Autowired
	private SysConfigRedis sysConfigRedis;

	@Autowired
	private CommonService commonService;

	@Autowired
	private RedisUtils redisUtils;

	/**
	 * 查询所有
	 * @return
	 */
	@Override
	public Collection queryCacheAll() {
		Collection list=sysConfigRedis.getBaseConfigList(commonService.getTenantId()+":config:*");
		if(CollectionUtils.isEmpty(list)){
			list=Lists.newArrayList();
			for (BaseConfigEntity distEntity : getLists()) {
				sysConfigRedis.setBaseConfig(commonService.getTenantId(),distEntity,distEntity.getParamKey());
				list.add(distEntity);
			}
		}
		return list;


	}

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String paramKey = (String)params.get("paramKey");

		IPage<BaseConfigEntity> page = this.page( new Query<BaseConfigEntity>().getPage(params), new QueryWrapper<BaseConfigEntity>() .like(StringUtils.isNotBlank(paramKey),"param_key", paramKey) .eq("status", 1)
		);

		return new PageUtils(page);
	}

	@Override
	public void saveConfig(BaseConfigEntity config) {

		if(!ShiroUtils.getSubject().hasRole(Constant.ROLE_SUPER_ADMIN)){
			config.setIsSystem(ValidEnum.NO.getValue());
		}
		this.save(config);
		sysConfigRedis.saveOrUpdate(config,String.format("%s:%s",commonService.getTenantId(),config.getParamKey()));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(BaseConfigEntity config) {
		BaseConfigEntity oldConfig=this.getById(config.getId());

		if(!ShiroUtils.getSubject().hasRole(Constant.ROLE_SUPER_ADMIN)
				&&oldConfig.getIsSystem()==ValidEnum.YES.getValue()){
			throw new RRException("非系统管理禁止修改系统参数");
		}
		this.updateById(config);
		sysConfigRedis.saveOrUpdate(config,String.format("%s:%s",commonService.getTenantId(),config.getParamKey()));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateValueByKey(String key, String value) {
		baseMapper.updateValueByKey(key, value);

		sysConfigRedis.delete(String.format("%s:%s",commonService.getTenantId(),key));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteBatch(Long[] ids) {
		for(Long id : ids){
			BaseConfigEntity config = this.getById(id);
			sysConfigRedis.delete(String.format("%s:%s",commonService.getTenantId(),config.getParamKey()));
		}

		this.removeByIds(Arrays.asList(ids));
	}

	@Override
	public String getValue(String key) {
		String configKey = RedisKeys.getBaseConfigKey(commonService.getTenantId(),key);
		BaseConfigEntity config =  redisUtils.get(configKey, BaseConfigEntity.class);
		if(config == null){
			config = baseMapper.queryByKey(key);
			sysConfigRedis.saveOrUpdate(config,String.format("%s:%s",commonService.getTenantId(),config.getParamKey()));
		}

		return config == null ? null : config.getParamValue();
	}

	@Override
	public <T> T getConfigObject(String key, Class<T> clazz) {
		String value = getValue(key);
		if(StringUtils.isNotBlank(value)){
			return new Gson().fromJson(value, clazz);
		}

		try {
			return clazz.newInstance();
		} catch (Exception e) {
			throw new RRException("获取参数失败");
		}
	}

	private List<BaseConfigEntity> getLists(){
		List<BaseConfigEntity> list= Lists.newArrayList();
		return list(getQueryWrapper(Maps.newLinkedHashMap()));
	}

	/**
	 * 获取查询条件
	 *
	 * @param
	 */
	private QueryWrapper<BaseConfigEntity> getQueryWrapper(Map<String, Object> params) {
		QueryWrapper<BaseConfigEntity> queryWrapper=new QueryWrapper<>();
		//queryWrapper.eq("is_valid",ValidEnum.YES.getValue());
		queryWrapper.orderByAsc("id");
		return queryWrapper;
	}
}
